import { ConfigService } from "@nestjs/config"
import chalk from "chalk";
import { WinstonModuleOptions } from "nest-winston";
import { format, transports } from "winston";
import "winston-daily-rotate-file";

export const winstonConfig = {
    inject: [ConfigService],
    useFactory: (configService: ConfigService) => {
        // 日志输出的管道
        const transportsList: WinstonModuleOptions["transports"] = [
            new transports.DailyRotateFile({
                level: "error",
                dirname: `logs`,
                filename: `%DATE%-error.log`,
                datePattern: "YYYY-MM-DD",
                maxSize: "20m",
                format: format.combine(
                    // format.label({ label: 'right meow!' }),
                    format.timestamp({
                        format: 'YYYY-MM-DD HH:mm:ss', 
                    }),
                    format.printf(({ level, message, timestamp }) => {
                        return `${timestamp} ${level}: ${message}`;
                    })
                )
            }),
            new transports.DailyRotateFile({
                level: configService.get('LOG_LEVEL') || 'debug',
                dirname: `logs`,
                filename: `%DATE%-combined.log`,
                datePattern: "YYYY-MM-DD",
                maxSize: "20m",
                format: format.combine(
                    format.timestamp({
                        format: 'YYYY-MM-DD HH:mm:ss', 
                    }),
                    format((info) => {
                        if (info.level === "error") {
                            return false; // 过滤掉'error'级别的日志
                        }
                        return info;
                    })(),
                    format.printf(({ level, message, timestamp }) => {
                        return `${timestamp} ${level}: ${message}`;
                    })
                )
            })
        ];
        // 开发环境下，输出到控制台
        if (process.env.NODE_ENV === "development") {
            transportsList.push(new transports.Console(
                {
                    level: configService.get('LOG_LEVEL') || 'debug',
                    format: format.combine(
                        format.colorize(),
                        format.timestamp({
                            format: 'YYYY-MM-DD HH:mm:ss', 
                        }),
                        format.printf(({ level, message, timestamp }) => {
                            const appStr = chalk.green(`[WINSTON]`);
                            return `${appStr} ${timestamp} ${level} ${message} `;
                        })
                    ),

                }
            ));
        }

        return {
            transports: transportsList
        };
    }
}

// const levels = {error: 0,warn: 1, info: 2,http: 3,verbose: 4,debug: 5,silly: 6};
// 当我们配置level为wran的时候，它会记录小于或等于当前等级的日志信息